<?php

declare (strict_types=1);
namespace App\Model;

use App\Constants\ErrorCode;
use App\Exception\ApiException;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;
/**
 */
class DiscountVideoUsers extends Model
{
    // 折扣视频价格
    const DISCOUNT_COIN = 20;

    // 男生展示优惠视频女用户的最大充值额度(单位: 分）
    const SHOW_PAY_LIMIT = 30000;

    // 女生加入特惠视频的通话时长限制
    const JOIN_DISCOUNT_VIDEO_CALL_LIMIT = 650;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'discount_video_users';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];

    /**
     * 加入特惠视频
     * @param int $userId
     * @return bool
     */
    public static function joinDiscountVideo($userId)
    {
        $model = self::getLog($userId);

        if (!empty($model)) {
            return true;
        }

        $model = new self();
        $model->user_id = $userId;
        $model->user_type = $userId;
        $model->join_time  = date('Y-m-d H:i:s');
        $model->created_at = date('Y-m-d H:i:s');
        $model->updated_at = date('Y-m-d H:i:s');

        return $model->save();
    }

    /**
     * 获取记录
     * @param int $userId
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public static function getLog($userId)
    {
        return self::where(['user_id' => $userId])->first();
    }

    /**
     * 退出特惠视频
     * @param int $userId
     * @return int|mixed
     */
    public static function quitDiscountVideo($userId)
    {
        self::where(['user_id' => $userId])->delete();

        DiscountVideoRank::quitDiscountVideo($userId);

        return true;
    }

    /**
     * @return array
     */
    public static function getUserList()
    {
        $query = self::orderBy('user_profile.online', 'desc')
            ->leftJoin('user_profile', 'user_profile.user_id', '=', 'discount_video_users.user_id')
            ->leftJoin('user', 'user_profile.user_id', '=', 'user.id')
            ->pluck('discount_video_users.user_id');

        return $query->toArray();
    }

    /**
     * 检查是否展示特惠视频（男）
     * @param $userId
     * @return bool
     */
    public static function checkShowPermissions($userId):bool
    {
        if (UserProfile::getGender($userId) != 1) {
            return false;
        }

        $payOrderTotal = PayOrder::getSuccessTotal($userId);
        if ($payOrderTotal >= self::SHOW_PAY_LIMIT) {
            return false;
        }

        return true;
    }

    /**
     * 检查是否展示特惠视频排名（女）
     * @param $userId
     * @return bool
     */
    public static function checkShowRankPermissions($userId):bool
    {
        log_info($userId, ['checkShowRankPermissions']);
        if (UserProfile::getGender($userId) != 0) {
            throw new ApiException('服务错误', ErrorCode::DEFAULT_ERROR);
        }

//        非真人认证
        $selfIsVrfy = UserProfile::checkAvatarVrfied($userId);
        if (!$selfIsVrfy) {
            throw new ApiException('平台提倡真实交友，请真人头像认证后再重试～', ErrorCode::REAL_AVATAR_NOT_VRFY);
        }

        $callTimeTotal = VideoCall::getCallNum('total_call_minutes', '', '', 0, $userId);
        $callTimeTotalChat = VideoCall::getCallNum('total_call_minutes', '', '', 0, 0, $userId);
        $diffCallTime = self::JOIN_DISCOUNT_VIDEO_CALL_LIMIT - $callTimeTotal - $callTimeTotalChat;
        if ($diffCallTime > 0) {
            throw new ApiException("加入失败，您的累计视频通话时长为{$callTimeTotal}分钟，距离加入视频特惠还有{$diffCallTime}分钟，请继续努力，或联系客服申请加入", ErrorCode::JOIN_DISCOUNT_VIDEO_FAIL);
        }

        return true;
    }

    /**
     * 检查是否展示特惠视频排名（女）
     * @param $userId
     * @return bool
     */
    public static function checkShowRankPermissionsV2($userId):bool
    {
        if (UserProfile::getGender($userId) != 0) {
            return false;
        }

//        非真人认证
        $selfIsVrfy = UserProfile::checkAvatarVrfied($userId);
        if (!$selfIsVrfy) {
            return false;
        }

        $callTimeTotal = VideoCall::getCallNum('total_call_minutes', '', '', 0, $userId);
        $callTimeTotalChat = VideoCall::getCallNum('total_call_minutes', '', '', 0, 0, $userId);
        $diffCallTime = self::JOIN_DISCOUNT_VIDEO_CALL_LIMIT - $callTimeTotal - $callTimeTotalChat;
        if ($diffCallTime > 0) {
            return false;
        }

        return true;
    }

    /**
     * 获取男女用户特惠视频状态
     * @param $userId
     * @return int  0-未大要求 1-男生已达要求/女生已达要求未加队列 2-女生已在队列
     */
    public static function getStatus($userId)
    {
        $gender = UserProfile::getGender($userId);

        $status = 0;
        if ($gender == 1) {
            if (DiscountVideoUsers::checkShowPermissions($userId)) {
                $status = 1;
            }
        } else {
            ## TODO 女生都显示
            $status = 1;
            if (DiscountVideoUsers::getLog($userId)) {
                $status = 2;
            }
        }

        return $status;
    }

    public static function addVideoInfo($userId, $videoCallTime)
    {
        $model = self::where(['user_id' => $userId])->first();

        if (empty($model)) {
            return false;
        }

        $model->video_call_num += 1;
        $model->video_call_time += $videoCallTime;

        return $model->save();
    }
}
